var prefix = jsctx + "/elecGun";

var elecGun = (function () {
    function init() {
        setTimeout(function () {//防止先于-读取缓存执行
            load();
        }, 10)
    };

    $('#exampleTable').on('load-success.bs.table', function (e, data) {
        if (data.total && !data.rows.length) {
            $('#exampleTable').bootstrapTable('selectPage').bootstrapTable('refresh');
        }
    });

    /**
     * 导出列表
     */
    function exportList() {
        $.fileDownload(prefix + "/exportGun", { // 后台请求链接
            httpMethod: "get",　　　　　　　　// 请求方式
            contentType: 'application/json',　 // 请求头
            data: {　　　　　　　　　　　　　　　// 参数，左边为后台接收的参数名，右边为前端获取的值，
                gunNo: $("#gunNo").val().trim(),
                status: $("#stationStaus").val().trim(),
                pileName: $("#pileSort").val().trim(),
                stationName: $("#stationName").val().trim(),
                operatorName: $("#operatorName").val().trim(),
                elecStationId: $("#elecStationId").val(),
                elecPileId: $("#elecPileId").val(),
                offset: $('.active .page-link').text(),
                limit: $(".page-size").text()
            },
            prepareCallback: function (url) {
                layer.msg("文件下载中...", {time: -1})
            },
            abortCallback: function (url) {
                // 异常终止
                layer.msg("文件下载异常！！");
            },
            successCallback: function (url) {
                layer.msg("文件下载成功！！", {time: 1500});
            },
            failCallback: function (data) {
                var str = "{" + data.substring(data.indexOf("{") + 1, data.indexOf("}")) + "}";
                layer.msg(JSON.parse(str).message);
            }
        })
    }

    function load() {
        $('#exampleTable')
            .bootstrapTable(
                {
                    method: 'get',
                    url: prefix + "/listElecGun",
                    iconSize: 'outline',
                    toolbar: '#exampleToolbar',
                    striped: false,
                    dataType: "json",
                    pagination: true,
                    singleSelect: false,
                    cache: false,
                    pageSize: 10,
                    pageList: [10],
                    pageNumber: 1,
                    sidePagination: "server",
                    queryParams: function (params) {
                        return {
                            limit: params.limit,
                            offset: (params.offset / params.limit) + 1,
                            elecStationId: $("#elecStationId").val(),
                            elecPileId: $("#elecPileId").val(),
                            gunNo: $("#gunNo").val().trim(),
                            status: $("#stationStaus").val().trim(),
                            pileName: $("#pileSort").val().trim(),
                            stationName: $("#stationName").val().trim(),
                            operatorName: $("#operatorName").val().trim(),
                        };
                    },
                    columns: [
                        {
                            title: '#', field: '', width: '50', align: 'left',
                            formatter: function (value, row, index) {
                                return index + 1;
                            }
                        },
                        {field: 'gunNo', title: '枪编号', width: '100', align: 'left'},
                        {field: 'gunNum', title: '枪顺序号', width: '100', align: 'left'},
                        {
                            field: 'status', title: '服务状态', width: '100', align: 'center',
                            formatter: function (value, row, index) {
                                if (value == 0) {
                                    return '<span class="label label-info">空闲</span>'
                                } else if (value == 1) {
                                    return '<span class="label label-danger">使用中</span>'
                                } else if (value == 2) {
                                    return '<span class="label label-danger">插抢中</span>'
                                } else if (value == 3) {
                                    return '<span class="label label-danger">已充满</span>'
                                } else if (value == 4) {
                                    return '<span class="label label-danger">离线</span>'
                                } else if (value == 5) {
                                    return '<span class="label label-danger">充电中</span>'
                                } else if (value == 6) {
                                    return '<span class="label label-danger">已结束</span>'
                                } else if (value == 7) {
                                    return '<span class="label label-danger">故障</span>'
                                }
                            }
                        },
                        {
                            field: 'nationalStandard', title: '枪型号',
                            width: '100', align: 'left'
                        },
                        {
                            field: '', title: '输出电压范围(V)', width: '100', align: 'center',
                            formatter: function (value, row, index) {
                                return '<span>' + row.voltageLowerLimits + '-' + row.voltageUpperLimits + '</span>'
                            }
                        },

                        {
                            field: 'current', title: '输出最大电流（A）',
                            width: '100', align: 'center',
                            formatter: function (value, row, index) {
                                return '<span>' + row.current + 'A</span>'
                            }
                        },
                        {field: 'hlhtManufacturerName', title: '生产厂商', width: '100', align: 'left'},
                        {field: 'hlhtManufacturerId', title: '出厂编号', width: '100', align: 'left'},
                        {field: 'stationName', title: '所属站点', width: '100', align: 'left'},
                        {field: 'pileName', title: '所属电桩', width: '100', align: 'left'},
                        {field: 'operatorName', title: '所属加盟商', width: '100', align: 'left'},
                        {
                            title: '操作',
                            field: 'roleId',
                            width: '200', align: 'center',
                            formatter: function (value, row, index) {


                                var a = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="编辑枪" onclick="elecGun.editElecGun(\''
                                    + row.elecGunId
                                    + '\')">编辑枪</a> ';

                                var b = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="详情" onclick="elecGun.detailElecGun(\''
                                    + row.elecGunId
                                    + '\')">详情</a> ';

                                var c = '<a class="btn btn-danger btn-sm ' + has_edit + '" href="#" title="删除" onclick="elecGun.deleteElecGun(\''
                                    + row.elecGunId
                                    + '\')">删除</a> ';

                                var q = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" title="二维码" onclick="elecGun.printElecGunQrCode(\''
                                    + row.gunNo
                                    + '\')">二维码</a> ';
                                if(!Elec_gun_look){
                                    //无查看权限
                                    b='';
                                    q='';

                                }
                                if (Elec_gun_update) {
                                    return a + c + b + q;
                                } else {
                                    return b + q;
                                }
                            }
                        }
                    ]
                });
    }

    function reLoad() {
        $('#exampleTable').bootstrapTable('refresh');
    }

    function addElecGun() {
        location.href = prefix + "/addElecGun";
    }

    function editElecGun(elecGunId) {
        location.href = prefix + "/editElecGun/" + elecGunId;
    }

    function detailElecGun(elecGunId) {
        location.href = prefix + "/detailElecGun/" + elecGunId;
    }

    function getArea() {
        var cityId = $("#cityId").val().trim();
        if (cityId == null || cityId == '') {
            $("#area").html("");
            var str = "<option value=''>行政区域</option>";
            $("#area").append(str);
        } else {
            $.ajax({
                url: prefix + "/getArea",
                type: "GET",
                data: {
                    cityId: cityId
                },
                error: function (request) {
                    parent.layer.alert("Connection error");
                },
                success: function (data) {
                    $("#areaId").html("");
                    var str = "<option value=''>--请选择--</option>";
                    if (data.status == 200) {
                        $.each(data.data, function (i, item) {
                            str += "<option value=" + item.areaId + ">" + item.areaName + "</option>";
                        })
                        $("#areaId").append(str);
                    } else {
                        // parent.layer.msg(data.message);
                        $("#areaId").val("");
                    }
                }
            });
        }

    }

    function getCity() {
        var provinceId = $("#provinceId").val().trim();
        if (provinceId == null || provinceId == '') {
            $("#city").html("");
            var str = "<option>市区</option>";
            $("#city").append(str);
        } else {
            $.ajax({
                url: prefix + "/getCity",
                type: "GET",
                data: {
                    provinceId: provinceId
                },
                error: function (request) {
                    parent.layer.alert("Connection error");
                },
                success: function (data) {
                    $("#cityId").html("");
                    var str = "<option value=''>--请选择--</option>";
                    if (data.status == 200) {
                        $.each(data.data, function (i, item) {
                            str += "<option value=" + item.cityId + ">" + item.cityName + "</option>";
                        })
                        $("#cityId").append(str);
                    } else {
                        // parent.layer.msg(data.message);
                        $("#cityId").val("");
                    }
                }
            });
        }

    }

    function printElecGunQrCode(gunNo) {
        // location.href = prefix + "/genElecGunQrCode/" + gunNo;
        layer.open({
            type: 2,
            title: '枪号：' + gunNo,
            shadeClose: false,
            area: ['350px', '300px'],
            content: prefix + '/genElecGunQrCode/' + gunNo
        });
    }

    function deleteElecGun(elecGunId) {
        layer.confirm('确定要删除选中的记录？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/deleteElecGun",
                type: "post",
                data: {
                    'elecGunId': elecGunId
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("删除成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }


    function goBack() {
        window.history.back();
    }

    return {
        init: init,
        goBack: goBack,
        reLoad: reLoad,
        addElecGun: addElecGun,
        deleteElecGun: deleteElecGun,
        editElecGun: editElecGun,
        detailElecGun: detailElecGun,
        getArea: getArea,
        getCity: getCity,
        exportList: exportList,
        printElecGunQrCode: printElecGunQrCode
    };
})();

var addElecGun = (function () {

    function init() {
        validateRule();
    };

    function getCheckedRoles() {
        var adIds = "";
        $("input:checkbox[name=role]:checked").each(function (i) {
            if (0 == i) {
                adIds = $(this).val();
            } else {
                adIds += ("," + $(this).val());
            }
        });
        return adIds;
    }

    function save() {
        var formData = new FormData($("#frmElecGun")[0]);
        //$("#roleIds").val(getCheckedRoles());
        $.ajax({
            cache: true,
            type: "POST",
            url: prefix + "/saveOrUpdateElecGun",
            data: formData,
            processData: false,
            contentType: false,
            error: function (request) {
                parent.layer.alert("Connection error");
            },
            success: function (data) {
                if (data.status == 200) {
                    parent.layer.msg("操作成功");
                    window.history.back();
                } else {
                    parent.layer.alert(data.message)
                }

            }
        });
    }

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frmElecGun").validate({
            rules: {
                gunNum: {
                    required: true
                }, nationalStandard: {
                    required: true
                }, voltageLowerLimits: {
                    required: true
                }, voltageUpperLimits: {
                    required: true
                }, current: {
                    required: true
                }, elecPileId: {
                    required: true
                }

            },
            messages: {
                gunNum: {
                    required: icon + "请输入枪序号",
                }, nationalStandard: {
                    required: icon + "请输入枪型号",
                }, voltageLowerLimits: {
                    required: icon + "请填写完整电压范围",
                }, voltageUpperLimits: {
                    required: icon + "请填写完整电压范围",
                }, current: {
                    required: icon + "请输入输出最大电流",
                }, elecPileId: {
                    required: icon + "请选择所属充电桩",
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    }

    return {
        init: init
    };
})();
